package com.example.leetcode.leetcode.hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author haitao
 * @date 2021/8/31 8:24 下午
 *
 * [2,3,3,5] 求数组中组合总和为39的
 */
public class Solution39 {

    List<List<Integer>> ans = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        trackBack(candidates, target, new ArrayList<>(),0);
        return ans;
    }

    public void trackBack(int[] candidates, int remains  ,List<Integer> path , int ix){

        if (remains == 0){
            ans.add(new ArrayList<>(path));
            return;
        }

        for (int i = ix; i < candidates.length; i++) {
            // 剪枝
            if (candidates[i]>remains){
                return;
            }
            path.add(candidates[i]);
            trackBack(candidates, remains - candidates[i], path, i);
            path.remove(path.size()-1);
        }
    }
}
